import { http } from "@/utils/http";
import type { ApiResponse } from "../../user";
import { ensureArray, normalisePagination, toNumber } from "@/api/_helpers";

const ORDER_BASE = "/system/order/orders";

export interface OrderItemSnapshot {
  id: number;
  product_id: number;
  sku_id: number | null;
  quantity: number;
  unit_price: number;
  subtotal: number;
  product_snapshot: Record<string, any>;
  create_time: string;
  update_time: string;
}

export interface OrderPaymentSnapshot {
  id: number;
  method: string;
  amount: number;
  pay_time: string | null;
  pay_data: Record<string, any>;
}

export interface OrderRefundSnapshot {
  id: number;
  refund_no: string;
  amount: number;
  status: number;
  status_label?: string;
  reason: string;
  evidence: Array<any>;
}

export interface OrderRecord {
  id: number;
  order_no: string;
  buyer_user_id: number;
  buyer_org_id: number;
  seller_user_id: number | null;
  seller_org_id: number;
  region_id: number | null;
  assist_user_id: number | null;
  source_channel: string;
  status: number;
  status_label: string;
  pay_status: number;
  ship_status: number;
  finish_status: number;
  refund_status: number;
  audit_status: number;
  audit_remark: string;
  audit_time: string | null;
  buyer_payable_amount: number;
  buyer_paid_amount: number;
  seller_receivable_amount: number;
  platform_commission_amount: number;
  shipping_fee: number;
  discount_amount: number;
  buyer_remark: string;
  seller_remark: string;
  internal_remark: string;
  amount_snapshot: Record<string, any>;
  paid_at: string | null;
  shipped_at: string | null;
  finished_at: string | null;
  cancelled_at: string | null;
  create_time: string;
  update_time: string;
  items: OrderItemSnapshot[];
  payments: OrderPaymentSnapshot[];
  refunds: OrderRefundSnapshot[];
}

export interface OrderListParams {
  page?: number;
  page_size?: number;
  keyword?: string;
  status?: string | number;
  pay_status?: string | number;
  ship_status?: string | number;
  refund_status?: string | number;
  finish_status?: string | number;
  audit_status?: string | number;
  buyer_org_id?: string | number;
  seller_org_id?: string | number;
  assist_user_id?: string | number;
  start_time?: string;
  end_time?: string;
}

export interface OrderListResult {
  list: OrderRecord[];
  pagination: {
    total: number;
    pageSize: number;
    currentPage: number;
  };
  raw: Record<string, any>;
}

const mapOrderItem = (item: Record<string, any>): OrderItemSnapshot => ({
  id: toNumber(item.id, 0),
  product_id: toNumber(item.product_id, 0),
  sku_id:
    item.sku_id !== undefined && item.sku_id !== null
      ? toNumber(item.sku_id, null)
      : null,
  quantity: toNumber(item.quantity, 0),
  unit_price: Number(item.unit_price ?? 0),
  subtotal: Number(item.subtotal ?? item.subtotal_amount ?? 0),
  product_snapshot: (item.product_snapshot as Record<string, any>) ?? {},
  create_time: item.create_time ?? "",
  update_time: item.update_time ?? ""
});

const mapPayment = (payment: Record<string, any>): OrderPaymentSnapshot => ({
  id: toNumber(payment.id, 0),
  method: payment.method ?? payment.pay_method ?? "",
  amount: Number(payment.amount ?? payment.pay_amount ?? 0),
  pay_time: payment.pay_time ?? null,
  pay_data: (payment.pay_data as Record<string, any>) ?? {}
});

const mapRefund = (refund: Record<string, any>): OrderRefundSnapshot => ({
  id: toNumber(refund.id, 0),
  refund_no: refund.refund_no ?? "",
  amount: Number(
    refund.amount ?? refund.refund_amount ?? refund.approved_amount ?? 0
  ),
  status: toNumber(refund.status, 0),
  status_label: refund.status_label ?? "",
  reason: refund.reason ?? "",
  evidence: ensureArray<any>(refund.evidence ?? [])
});

const mapOrderRecord = (record: Record<string, any>): OrderRecord => ({
  id: toNumber(record.id, 0),
  order_no: record.order_no ?? "",
  buyer_user_id: toNumber(record.buyer_user_id, 0),
  buyer_org_id: toNumber(record.buyer_org_id, 0),
  seller_user_id:
    record.seller_user_id !== undefined && record.seller_user_id !== null
      ? toNumber(record.seller_user_id, null)
      : null,
  seller_org_id: toNumber(record.seller_org_id, 0),
  region_id:
    record.region_id !== undefined && record.region_id !== null
      ? toNumber(record.region_id, null)
      : null,
  assist_user_id:
    record.assist_user_id !== undefined && record.assist_user_id !== null
      ? toNumber(record.assist_user_id, null)
      : null,
  source_channel: record.source_channel ?? "",
  status: toNumber(record.status, 0),
  status_label: record.status_label ?? "",
  pay_status: toNumber(record.pay_status, 0),
  ship_status: toNumber(record.ship_status, 0),
  finish_status: toNumber(record.finish_status, 0),
  refund_status: toNumber(record.refund_status, 0),
  audit_status: toNumber(record.audit_status, 0),
  audit_remark: record.audit_remark ?? "",
  audit_time: record.audit_time ?? null,
  buyer_payable_amount: Number(record.buyer_payable_amount ?? 0),
  buyer_paid_amount: Number(record.buyer_paid_amount ?? 0),
  seller_receivable_amount: Number(record.seller_receivable_amount ?? 0),
  platform_commission_amount: Number(record.platform_commission_amount ?? 0),
  shipping_fee: Number(record.shipping_fee ?? 0),
  discount_amount: Number(record.discount_amount ?? 0),
  buyer_remark: record.buyer_remark ?? "",
  seller_remark: record.seller_remark ?? "",
  internal_remark: record.internal_remark ?? "",
  amount_snapshot: (record.amount_snapshot as Record<string, any>) ?? {},
  paid_at: record.paid_at ?? null,
  shipped_at: record.shipped_at ?? null,
  finished_at: record.finished_at ?? null,
  cancelled_at: record.cancelled_at ?? null,
  create_time: record.create_time ?? "",
  update_time: record.update_time ?? "",
  items: ensureArray<Record<string, any>>(record.items ?? []).map(mapOrderItem),
  payments: ensureArray<Record<string, any>>(record.payments ?? []).map(
    mapPayment
  ),
  refunds: ensureArray<Record<string, any>>(record.refunds ?? []).map(mapRefund)
});

const sanitiseParams = (params: OrderListParams) => {
  const result: Record<string, any> = {};
  Object.entries(params).forEach(([key, value]) => {
    if (value === undefined || value === null || value === "") return;
    result[key] = value;
  });
  return result;
};

const fetchList = async (
  params: OrderListParams = {}
): Promise<OrderListResult> => {
  const page = toNumber(params.page, 1);
  const pageSize = toNumber(params.page_size, 10);

  const res = await http.request<ApiResponse<any>>("get", ORDER_BASE, {
    params: sanitiseParams({
      ...params,
      page,
      page_size: pageSize
    })
  });

  const payload = (res?.data as Record<string, any>) ?? {};
  const listSource =
    payload.list ?? payload.data ?? payload.records ?? payload.items ?? [];
  const list = ensureArray<Record<string, any>>(listSource).map(mapOrderRecord);

  const pagination = normalisePagination(
    payload.pagination ?? payload,
    page,
    pageSize,
    list.length
  );

  return {
    list,
    pagination,
    raw: payload
  };
};

const fetchDetail = async (id: number | string): Promise<OrderRecord> => {
  const res = await http.request<ApiResponse<any>>(
    "get",
    `${ORDER_BASE}/${id}`
  );
  const payload = (res?.data as Record<string, any>) ?? {};
  return mapOrderRecord(payload);
};

export default {
  fetchList,
  fetchDetail
};
